<?php
define ('TEST_USER_ID', 2);
require_once '../common.php';

$item_x = $_POST['x'];
$item_y = $_POST['y'];

$result = sys::sql("select * from test_items where item_x=%d && item_y=%d;",
	$item_x, $item_y);

if (empty($result) || empty($result[0]))
{
	$valid_result = get_map_valid_xy($item_x, $item_y);
	if ($valid_result == 0)
	{
		$message = "有效陆地，可以创建。";
	}
	else if ($valid_result == -1)
	{
		$message = "超出地图边界，无法创建。";
	}
	else if ($valid_result == -2)
	{
		$message = "不是陆地，无法创建。";
	}

	echo json_encode(array("result"=>$valid_result, "message"=>$message));
}
else
{
	$item_info = item::appendImageRealUrl($result[0]);
	$item_info['result'] = true;
	$item_info['item_image'] = $item_info['item_image_l'];
	$image_file = $_SERVER['DOCUMENT_ROOT'].$item_info['item_image_l'];
	$image_info = getimagesize($image_file);
	$item_info['item_image_width'] = $image_info[0];
	$item_info['item_image_height'] = $image_info[1];
	//echo json_encode(array_merge(array("result"=>true), $item_info));
	echo json_encode($item_info);
}

function get_map_valid_xy($x, $y)
{
	$image = imagecreatefromgif('worldmap.gif');
	$rgb = imagecolorsforindex($image,
		imagecolorat($image, $x, $y));
	
	// out of border	
	if ($x<0 || $y<0 || $x>=imagesx($image) || $y>=imagesy($image))
	{
		return -1;
	}
	else
	{
		// can not build - sea or not land
		if (array_sum($rgb) != 255*3)
		{
			return -2;
		}
		// land - can build
		else
		{
			return 0;
		}
	}
}